/**
 * @author: lihai
 * @description: 全局背景音频播放器
 * 
 * 修改记录：
 * 2019年7月12日 16:07:13
 * 1. onEnded()方法中加入返回值判断，如果没有返回true，则调用onPlayEnd方法
 * 2. 增加isEnd判断
 * 
 * 2019年8月2日 15:30:14
 * 1. 增加对当前页面关于播放器状态的回调：onAudioPlayerStatusChange()
 * 
 * 2020年2月17日 12:02:08
 * 1. 增加onTimeUpdate，并且在播放结束时再调一次
 * 
 * 2020年3月2日 16:40:06
 * 1. 增加 item 操作，add、remove、在_curItem播放时，通知停止其他item的播放
 * 
 * 2020年9月7日 18:29:18
 * 1. 判断，当企业微信中打开时，使用内部音频播放器，否则使用背景音频播放器
 * 
 * 2020年9月22日 17:19:18
 * 1. 增加内部音频播放，判断同一时间只能有一个音频播放
 */
import Util from "./util.js";
const wxapi = uni;

const BgAudioPlayer = {
	manage: null,
	is_play: false,
	pageLocation: '',
	thumb: '',
	isDelayAudio: false,
	isInit: false,
	isEnd: true,
	init: function() {
		if (this.isInit) {
			return;
		}

		if (this.manage == null) {
			let systemInfo = wxapi.getSystemInfoSync();

			if (systemInfo.environment == 'wxwork') {
				this.manage = wxapi.createInnerAudioContext();
				console.log('创建内部音频播放器');
			} else {
				this.manage = wxapi.getBackgroundAudioManager();
				console.log('创建背景音频播放器');
			}
		}

		this.isInit = true;
		var self = this;
		this.manage.onEnded(() => {
			this.is_play = false;

			if (this._curItem) {
				if (!this._curItem.onStatusChange('ended')) {
					this.onPlayEnd();
					this.isEnd = true;
				}

				this._curItem.onTimeUpdate && this._curItem.onTimeUpdate({
					currentTime: 0
				});
			} //以下将遗弃


			if (!self.onStatusChange('ended')) {
				this.onPlayEnd();
				this.isEnd = true;
			}

			_triggerPage('ended');

			this._onTimeUpdate && this._onTimeUpdate({
				currentTime: 0
			});
		});
		this.manage.onPlay(() => {
			this.is_play = true;
			this.isEnd = false;
			let duration = this.manage.duration;

			if (this._curItem) {
				this._curItem.onStatusChange('play');
			} // 如果背景音频播放器播放中，停止他


			InnerAudioPlayer.is_play && InnerAudioPlayer.stop(); //以下将遗弃      

			this.onStatusChange('play');

			_triggerPage('play');
		});
		this.manage.onPause(() => {
			this.is_play = false;
			this.onPlayEnd();

			if (this._curItem) {
				this._curItem.onStatusChange('pause');
			} //以下将遗弃  


			this.onStatusChange('pause');

			_triggerPage('pause');
		});
		this.manage.onStop(() => {
			this.is_play = false;
			this.onPlayEnd();
			this.isEnd = true;

			if (this._curItem) {
				this._curItem.onStatusChange('stop');

				this._curItem.onTimeUpdate && this._curItem.onTimeUpdate({
					currentTime: 0
				});
			} //以下将遗弃 


			this.onStatusChange('stop');

			_triggerPage('stop');

			this._onTimeUpdate && this._onTimeUpdate({
				currentTime: 0
			});
		});
		this.manage.onError(e => {
			console.log('error');
			console.error(e); // 发生错误，当作是播放结束时间进行回调，确保下一段音频能被触发，暂时尝试

			this.is_play = false;

			if (this._curItem) {
				if (!this._curItem.onStatusChange('ended')) {
					this.onPlayEnd();
					this.isEnd = true;
				}

				this._curItem.onTimeUpdate && this._curItem.onTimeUpdate({
					currentTime: 0
				});
			} //以下将遗弃 


			if (!this.onStatusChange('ended')) {
				this.onPlayEnd();
				this.isEnd = true;
			}

			_triggerPage('ended');

			this._onTimeUpdate && this._onTimeUpdate({
				currentTime: 0
			});
		});
		this.manage.onTimeUpdate(ret => {
			// console.log(`onTimeUpdate`, ret);
			let duration = this.manage.duration;
			var currentTime = this.manage.currentTime;

			if (this._curItem) {
				// console.log(`${this._curItem.index}进行onTimeUpdate`);
				this._curItem.onTimeUpdate && this._curItem.onTimeUpdate({
					currentTime: currentTime
				});
			} //以下将遗弃


			this._onTimeUpdate && this._onTimeUpdate({
				currentTime: currentTime
			});
		});
	},
	play: function() {
		this.manage && this.manage.play();
	},
	pause: function() {
		this.manage && this.manage.pause();
	},
	stop: function() {
		this.manage && this.manage.stop();
	},
	playObj: function(playObj) {
		console.log(playObj);
		// 音频的数据源，默认为空字符串，当设置了新的 src 时，会自动开始播放 ，目前支持的格式有 m4a, aac, mp3, wav
		this.manage.src = playObj.src || playObj.CurAudioLink;
		this.manage.title = playObj.title || playObj.articleName; // 音频标题

		this.manage.epname = playObj.epname || playObj.lessonName; // 专辑名

		this.manage.singer = playObj.singer || ''; // 歌手名

		this.manage.coverImgUrl = playObj.coverImgUrl || playObj.poster; // 封面图url

		this.isDelayAudio = playObj.isDelayAudio == true; //当前播放的音频是否用于延迟

		this.thumb = playObj.coverImgUrl || playObj.poster;
	},
	playingData: { //正在播放的音频的业务信息
		// pageName: '', // 'audioList ,'dictation'
		// bookID: '',
		// unitID: ''
	},
	onStatusChange: function(status) {},
	onPlayEnd: function() {
		
	},
	onPageHide: function() {},
	onTimeUpdate: function(func) {
		this._onTimeUpdate = func;
	},
	// 新增的接口，以item为实例
	_curItem: null,

	get curItem() {
		return this._curItem;
	},

	itemList: [],
	attach: function(_item) {
		let self = this;
		self.init();
		let item = _item || {}; // 对item的方法进行扩展，直接操作item即可

		item._quickStop = function() {
			item.pause();
			item.onStatusChange('pause');
			item.onTimeUpdate({
				currentTime: 0
			});
		};

		item.play = function() {
			if (self._curItem && self._curItem != item) {
				self._curItem._quickStop();

				self.playObj(item.playObj);
				self._curItem = item;
			}

			self.manage.play();
			console.log(`${item.index}?操作play`);
		};

		item.start = function(obj) {
			item.playObj = obj;

			if (self._curItem && self._curItem != item) {
				self._curItem._quickStop();
			}

			self._curItem = item;
			self.playObj(item.playObj);
			self.manage.play();
			console.log(`${item.index}?操作start`);
		};

		item.pause = function() {
			self.manage.pause();
		};

		item.stop = function() {
			self.manage.stop();
		};

		item.onStatusChange = item.onStatusChange || function(status) {};

		item.onPageHide = item.onPageHide || function() {};

		item.onTimeUpdate = item.onTimeUpdate || function(ret) {};

		item.getDuration = () => {
			return this.manage.duration;
		};

		item.seek = time => {
			return this.manage.seek(time);
		};

		if (this.itemList.indexOf(item) == -1) {
			this.itemList.push(item);
		} else {
			console.error('已经绑定过');
		}

		return item;
	},
	detach: function(item, force) {
		// 正在播放中的不能解绑
		if (this.is_play && this._curItem == item) {
			if (force) {
				// 播放中的强制解绑
				this.manage.stop();
			} else {
				return;
			}
		}

		var index = this.itemList.indexOf(item);

		if (index > -1) {
			this.itemList.splice(index, 1);
		}

		if (item == this._curItem) {
			this._curItem = null;
		}
	}
};

function _triggerPage(str) {

	let curData = Util.getCurPage();

	if (curData && curData.$vm && curData.$vm.onAudioPlayerStatusChange != null) {
		curData.$vm.onAudioPlayerStatusChange(str);
	}
}

const InnerAudioPlayer = {
	is_play: false,

	playUrl(url) {
		let self = this;

		if (!self.innerAudioContext) {
			self.innerAudioContext = wxapi.createInnerAudioContext();
			self.innerAudioContext.autoplay = false;
			self.innerAudioContext.onPlay(() => {
				if (self._statusChangeListener && self._statusChangeListener.onPlay) {
					self._statusChangeListener.onPlay();
				}

				self.is_play = true; // 如果背景音频播放器播放中，停止他

				BgAudioPlayer.is_play && BgAudioPlayer.stop();
			});
			self.innerAudioContext.onEnded(() => {
				console.log('结束播放');

				if (self._statusChangeListener && self._statusChangeListener.onEnded) {
					self._statusChangeListener.onEnded();
				}

				self.is_play = false;
			});
			self.innerAudioContext.onStop(() => {
				console.log('停止播放');

				if (self._statusChangeListener && self._statusChangeListener.onStop) {
					self._statusChangeListener.onStop();
				}

				self.is_play = false;
			});
			self.innerAudioContext.onError(res => {
				console.error('结束出错', res);

				if (self._statusChangeListener && self._statusChangeListener.onError) {
					self._statusChangeListener.onError();
				}

				self.is_play = false;
			});
		}

		self.innerAudioContext.src = url;
		self.innerAudioContext.play();
	},

	stop() {
		let self = this;
		self.innerAudioContext.stop();
	},

	_statusChangeListener: null,

	setOnStatusChange(statusChangeListener) {
		this._statusChangeListener = statusChangeListener;
	}

};
/**
 * 停止所有音频播放
 */

function stopAudio() {
	BgAudioPlayer.is_play && BgAudioPlayer.stop();
	InnerAudioPlayer.is_play && InnerAudioPlayer.stop();
}

function setAllAudioDisable(disable) {
	if (InnerAudioPlayer._statusChangeListener && InnerAudioPlayer._statusChangeListener.onDisableChange) {
		InnerAudioPlayer._statusChangeListener.onDisableChange(disable);
	}

	if (BgAudioPlayer.itemList) {
		for (let i = 0; i < BgAudioPlayer.itemList.length; i++) {
			if (BgAudioPlayer.itemList[i].onDisableChange && BgAudioPlayer.itemList[i].onDisableChange) {
				BgAudioPlayer.itemList[i].onDisableChange(disable);
			}
		}
	}
}

export default {
	BgAudioPlayer: BgAudioPlayer,
	InnerAudioPlayer: InnerAudioPlayer,
	stopAudio: stopAudio,
	setAllAudioDisable
};